import pymysql


class DBUtil:
    # 定义变量
    conn = None

    # 封装数据库连接的方法
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 封装数据库关闭的方法
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 封装查询数据库的方法
    @classmethod
    def query_db(cls, sql):
        # 定义变量
        cursor = None
        result = None
        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql,获取结果集，返回结果
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print("读取数据库操作出错:", str(err))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_db()
            return result

    # 封装增删改数据库的方法
    @classmethod
    def uid_db(cls, sql):
        cursor = None

        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql
            cursor.execute(sql)
            affencted_rows = cls.conn.affected_rows()
            print("影响的行数", affencted_rows)
            # 事务的提交、回滚
            cls.conn.commit()
        except Exception as err:
            print("数据库操作错误:", str(err))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_db()

    pass


if __name__ == '__main__':
    # query_sql = "select * from t_book;"
    # res = DBUtil.query_db(query_sql)
    # print("res=", res)

    sql = "delete  from bs_user where mobile = '13989203950';"
    DBUtil.uid_db(sql)

    pass

